package test;

/**
 * @author WYC
 * @version 1.0
 * @ClassName DecoratorExample
 * @date 2024/12/14 0:59
 * @description
 */
// 组件接口
interface Coffee {
    double cost();
    String ingredients();
}

// 具体组件 - 普通咖啡
class SimpleCoffee implements Coffee {
    public double cost() {
        return 5.0;
    }

    public String ingredients() {
        return "咖啡";
    }
}

// 装饰器类
abstract class CoffeeDecorator implements Coffee {
    protected Coffee decoratedCoffee;

    public CoffeeDecorator(Coffee coffee) {
        this.decoratedCoffee = coffee;
    }

    public double cost() {
        return decoratedCoffee.cost();
    }

    public String ingredients() {
        return decoratedCoffee.ingredients();
    }
}

// 具体装饰器 - 牛奶
class MilkDecorator extends CoffeeDecorator {
    public MilkDecorator(Coffee coffee) {
        super(coffee);
    }

    public double cost() {
        return decoratedCoffee.cost() + 1.5;
    }

    public String ingredients() {
        return decoratedCoffee.ingredients() + ", 牛奶";
    }
}

// 具体装饰器 - 糖
class SugarDecorator extends CoffeeDecorator {
    public SugarDecorator(Coffee coffee) {
        super(coffee);
    }

    public double cost() {
        return decoratedCoffee.cost() + 0.5;
    }

    public String ingredients() {
        return decoratedCoffee.ingredients() + ", 糖";
    }
}

public class DecoratorExample {
    public static void main(String[] args) {
        // 创建普通咖啡
        Coffee simpleCoffee = new SimpleCoffee();
        System.out.println("价格: " + simpleCoffee.cost() + " 元, 成分: " + simpleCoffee.ingredients());

        // 添加牛奶
        Coffee milkCoffee = new MilkDecorator(simpleCoffee);
        System.out.println("价格: " + milkCoffee.cost() + " 元, 成分: " + milkCoffee.ingredients());

        // 添加糖
        Coffee milkSugarCoffee = new SugarDecorator(milkCoffee);
        System.out.println("价格: " + milkSugarCoffee.cost() + " 元, 成分: " + milkSugarCoffee.ingredients());
    }
}
